<template>
	<a-modal v-bind="options">
		<a-form ref="formRef" layout="vertical" :model="formData">
			<a-typography-paragraph strong>
				<blockquote>入住人信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="12">
					<a-form-item ref="employeeName" label="姓名" name="employeeName">
						<a-input-group compact class="display-flex">
							<a-input disabled :maxlength="20" v-model:value="formData.name" style="flex: 1" placeholder="请输入员工姓名" />
							<a-form-item-rest>
								<a-radio-group v-model:value="formData.gender" button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item ref="employeeName" label="客户来源" name="employeeName">
						<a-select
							v-model:value="formData.customerResource"
							placeholder="请选择客户来源"
							:options="sources"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME"
							@change="handlerChange('customerResource')" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="收付款账号：">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="formData.paymentType"
									:options="paymentAccountList"
									placeholder="请选择类型"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input v-model:value.trim="formData.paymentNo" placeholder="请输入账号" :maxlength="30" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="职业：">
						<a-select
							v-model:value="formData.profession"
							placeholder="请选择职业"
							:options="occupation"
							allow-clear
							show-search
							@change="handlerChange('profession')" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="工作单位：">
						<a-input v-model:value.trim="formData.employer" placeholder="请输入工作单位" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="重点人群：">
						<a-select
							v-model:value="formData.keyGroupsType"
							placeholder="请选择重点人群"
							:options="keyGroups"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME"
							@change="handlerChange('keyGroupsType')" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="爱好：">
						<!-- <a-tooltip :title="hobbiesData.join('，') || '请选择爱好'" destroy-tooltip-on-hide> -->
						<a-select
							v-model:value="formData.interestList"
							placeholder="请选择爱好"
							mode="multiple"
							:options="hobbies"
							allow-clear
							show-search
							max-tag-count="responsive"
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
						<!-- </a-tooltip> -->
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="证件照片：" name="frontImgUrl" :rules="[{required: contractDecision.cardPhoto, message: '请补充证件照片'}]">
						<a-button type="primary" block @click="visibles.certificate = true">
							<template v-if="formData.frontImgUrl || formData.rearImgUrl">
								<check-outlined />
							</template>
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>紧急联系人信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="12">
					<a-form-item
						label="紧急联系人："
						:rules="[{required: contractDecision.emergencyName, message: '请输入紧急联系人'}]"
						name="emergencyName">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="formData.emergencyType"
									:options="relationshipList"
									placeholder="关系"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								v-model:value="formData.emergencyName"
								@blur="formData.emergencyName = formData.emergencyName?.trim()"
								placeholder="请输入联系人姓名"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item
						label="紧急联系人手机号："
						:rules="[
							{required: contractDecision.emergencyName, message: '请输入紧急联系人电话'},
							{
								pattern: checkPhone,
								message: '手机号格式不正确'
							}
						]"
						name="emergencyPhone">
						<a-input-group compact>
							<a-input
								v-model:value.trim="formData.emergencyPhone"
								@blur="formData.emergencyPhone = formData.emergencyPhone?.trim()"
								:maxlength="11"
								placeholder="请输入联系人手机号" />
						</a-input-group>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-modal>
	<!-- 证件上传 -->
	<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="formData" />
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, computed, watch, onMounted} from 'vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {paymentAccountList, occupation, relationshipList} from '@/utils'
	import {DIC_PID_MAP, DEFAULT_FIELD_NAME} from 'yuxin-base/src/constant'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {CheckOutlined, PlusOutlined} from '@ant-design/icons-vue'
	import {message} from 'ant-design-vue'
	import {checkPhone} from '@/utils/check'
	// import {renterContractRules} from '@/rules/contract'

	const emits = defineEmits(['update:visible', 'success'])

	const props = defineProps<{
		visible: boolean
		dataSource: any
	}>()

	const formRef = ref()

	const options = reactive({
		width: 640,
		title: '编辑租客信息',
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
		},
		onOk() {
			updateFun()
		}
	})

	const formData = reactive({
		name: null,
		// 1男 2 女
		gender: 1,
		// 客户来源
		customerResource: null,
		//付款类型
		paymentType: 1,
		// 付款账号
		paymentNo: '',
		// 职业
		profession: null,
		//工作单位
		employer: '',
		// 重点人群
		keyGroupsType: null,
		// 爱好
		interestList: [],
		// 证件照片
		frontImgUrl: '',
		rearImgUrl: '',
		// 紧急联系人关系
		emergencyType: '1',
		// 紧急联系人姓名
		emergencyName: '',
		// 紧急联系人电话
		emergencyPhone: ''
	})

	const visibles = reactive({
		//证件照
		certificate: false
	})

	const contractDecision = ref({
		emergencyName: false,
		cardPhoto: false
	})

	// 客户来源
	const sources = ref<any>([])
	// 重点人群
	const keyGroups = ref<any>([])
	// 爱好
	const hobbies = ref<any>([])

	// 获取字典
	const getDics = () => {
		settingApi.getDicListByPidAll(DIC_PID_MAP['CUSTOMER@HOBBY']).then(({data}) => (hobbies.value = data))
		settingApi.getDicListByPidAll(DIC_PID_MAP['CUSTOMER@KEY_GROUPS']).then(({data}) => (keyGroups.value = data))
		settingApi.getDicListByPidAll(DIC_PID_MAP['CUSTOMER@CHANNELSOURCE']).then(({data}) => (sources.value = data))
	}

	onMounted(() => {
		getDics()
	})

	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				for (let key in props.dataSource) {
					if (formData.hasOwnProperty(key)) {
						if (props.dataSource[key]) {
							formData[key] = props.dataSource[key]
						}
					}
				}
				formData.interestList = props.dataSource.interest ? props.dataSource.interest?.split('/') : []
				getContractDecision()
			} else {
				for (let key in formData) {
					formData[key] = null
				}
				formData.frontImgUrl = ''
				formData.rearImgUrl = ''
			}
		}
	)

	/** 获取决策合同设置 */
	const getContractDecision = async () => {
		await settingApi.getDecisionList({bizPoint: 'CONTRACT_FIELD_MUST', module: 'CONTRACT'}).then(res => {
			let source = JSON.parse(res.data[0]?.value || '[]')
			contractDecision.value.emergencyName = source.includes(1) ? true : false
			contractDecision.value.cardPhoto = source.includes(3)
		})
	}
	// 保存
	const updateFun = async () => {
		if (await isDisabledF()) return

		formRef.value?.validate().then(() => {
			settingApi
				.updateTenant({
					...formData,
					customerResource: formData.customerResource || '',
					profession: formData.profession || '',
					keyGroupsType: formData.keyGroupsType || '',
					id: props.dataSource?.id,
					rearImgUrl: formData.rearImgUrl || '',
					frontImgUrl: formData.frontImgUrl || ''
				})
				.then((res: any) => {
					emits('update:visible', false)
					emits('success')
				})
		})
	}

	const handlerChange = (data: string) => {
		switch (data) {
			case 'customerResource':
				formData.customerResource = formData.customerResource ? formData.customerResource : null
				break
			case 'profession':
				formData.profession = formData.profession ? formData.profession : null
				break
			case 'keyGroupsType':
				formData.keyGroupsType = formData.keyGroupsType ? formData.keyGroupsType : null
				break
		}
	}

	const isDisabledF = async () => {
		const dics = [
			{data: formData.interestList, pid: DIC_PID_MAP['CUSTOMER@HOBBY'], type: 'array'},
			{data: formData.keyGroupsType, pid: DIC_PID_MAP['CUSTOMER@KEY_GROUPS']},
			{data: formData.customerResource, pid: DIC_PID_MAP['CUSTOMER@CHANNELSOURCE']}
		]
		for (const dic of dics) {
			if (dic.type === 'array') {
				if (!dic.data.length) continue
				const use = await settingApi.getDicListByPid(dic.pid)
				if (dic.data.some(a => use.data.every(v => v.id !== a))) {
					return message.error('选项已禁用，请选择其他选项！')
				}
			} else {
				if (!dic.data) continue
				const use = await settingApi.getDicListByPid(dic.pid)
				if (use.data.every(v => v.id !== dic.data)) {
					return message.error('选项已禁用，请选择其他选项！')
				}
			}
		}
	}
</script>

<style scoped></style>
